package com.tql.pandian.service.impl;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.ruoyi.common.core.constant.CommonUtil;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.CalculatedValueUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.datasource.annotation.Slave;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.RemoteKingdeeService;
import com.tql.pandian.entity.*;
import com.tql.pandian.entity.dto.SimpleDto;
import com.tql.pandian.mapper.TqlStapProlossMapper;
import com.tql.pandian.service.ITqlHllShopBillFoodService;
import com.tql.pandian.util.BusinessUtil;
import com.tql.pandian.vo.TqlPandianPeriodVO;
import com.tql.pandian.vo.TqlStapProlossItemVO;
import com.tql.pandian.service.ICommonService;
import com.tql.pandian.service.IGenCostAnalysService;
import com.tql.pandian.util.TimeUtil;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class GenCostAnalysService implements IGenCostAnalysService {

    @Autowired
    private ICommonService commonService;

    @Autowired
    private TqlStapProlossMapper tqlStapProlossMapper;

    @Autowired
    private RemoteKingdeeService remoteKingdeeService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ITqlHllShopBillFoodService tqlHllShopBillFoodService;


    //0.查询当前时间段,当前店铺所有的销售菜单
    //1.-- 备份库
    // 某个店某个时间段销售菜品
    /**
     select foodCode,count(1) as count from tql_hll_shop_bill_food10
     where shopID='76591358'
     and reportDate=20221012
     GROUP BY foodCode
     --tql_hll_shop_bill_food_reportDay1

     shopID,foodCode,foodName,shopId,foodCount
     //2.--主库
     /**
     select u.price from tql_food f
     inner join tql_food_unit u on f.foodID=u.foodID
     where foodCode in(
     01047,
     01071,
     01073,
     01075
     )
     and f.foodCategoryCode  in(select foodCategoryCode  from tql_shop_food_category where flag=0)
     //3.
     把这个数据 shopID,foodCode,foodCount求和,price,sum=price*count,pandianPeriodCode组成一条记录

     */

    //前面三步应该做成定时任务

    public TqlStapProlossItem getC(){
        return new TqlStapProlossItem();
    }
    /**
     * @param pandianCode
     */

    private final static String pandianKey = "pandian_gen_key";
//    @Override
//    public void gen(String pandianCode) {
//
//    }

    public int enrichData(String pcode) {
        String localDate = TimeUtil.longDatetoDate(pcode);
        String yyyymmdd = TimeUtil.getCurrentDate();
        if (Long.parseLong(pcode) < Long.parseLong(yyyymmdd)) {
             localDate = LocalDate.now().toString();
//            remoteKingdeeService.saveMaterialIncase(localDate);
//            remoteKingdeeService.saveMaterialTransferin(localDate);
//            remoteKingdeeService.saveMaterialTransferout(localDate);
//            tqlHllShopBillFoodService.insertBillFoodReportDay();
//            tqlHllShopBillFoodService.insertStapOutChange(0);

            String finalLocalDate = localDate;
            CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> remoteKingdeeService.saveMaterialIncase(finalLocalDate));
            String finalLocalDate1 = localDate;
            CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> remoteKingdeeService.saveMaterialTransferin(finalLocalDate1));
            String finalLocalDate2 = localDate;
            CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> remoteKingdeeService.saveMaterialTransferout(finalLocalDate2));
            CompletableFuture<Void> task4 = CompletableFuture.runAsync(() -> tqlHllShopBillFoodService.insertBillFoodReportDay());
            CompletableFuture<Void> task5 = CompletableFuture.runAsync(() -> tqlHllShopBillFoodService.insertStapOutChange(0));

            CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3, task4, task5);
            allTasks.join(); // 等待所有任务完成
           return 1;

        }
        else {
            return 2;
        }
    }

    public List<TqlHllShopBillFoodPeriod> insertBillFoodPeriodFromBillFoodReport(String pandianCode, TqlPandianPeriodVO period) throws ParseException {
        String yyyymm = StringUtils.getPandianCodeInfo(pandianCode, 2);
        //20240208
        String yyyyMMdd = period.getPcode();
        int month = TimeUtil.getMonth(yyyyMMdd, "yyyyMMdd");
        String tqlHllShopBillFoodReportDay = CommonUtil.TableName_ShopBillFoodReportDayDetail + month;
        String shopIdStr = commonService.getEnabledHllShopIdByKingdeeFnumber(period.getDeptCode());
        if (StringUtils.isEmpty(shopIdStr)) {
            throw new ServiceException("数据异常，未查到店铺数据！");
        }
        Long shopId = Long.parseLong(shopIdStr);
        //20240223 - 20240229
        Long std = Long.parseLong(TimeUtil.getStringDate(period.getStarttime()));
        Long etd = Long.parseLong(TimeUtil.getStringDate(period.getEndtime()));
        List<TqlHllShopBillFoodPeriod> list = commonService.getTqlHllShopBillFoodReportDayList(tqlHllShopBillFoodReportDay,pandianCode, yyyymm, shopId, std, etd);
        if (!list.isEmpty()) {
            commonService.insertTqlHllShopBillFoodPeriod(pandianCode, list);
        }
        return list;
    }

    public void insertBomcardAnalys(String pandianCode, List<TqlHllShopBillFoodPeriod>  list1, List<TqlStapProloss> prolossData) throws ParseException {
        String fnumber = StringUtils.getPandianCodeInfo(pandianCode, 1);
        String yyyymm = StringUtils.getPandianCodeInfo(pandianCode, 2);
//        String monthStr = yyyymm.substring(4);
//        int month = Integer.parseInt(monthStr);
        int month=TimeUtil.getMonth(yyyymm,"yyyyMMdd");
        //该门店所有做过BOM的菜品
        List<FoodAndBom> hasBomFoods = commonService.findFoodAndBom(fnumber);
        if (CollectionUtils.isEmpty(hasBomFoods)) return;
        String[] foodCodes = hasBomFoods.stream().map(FoodAndBom::getFoodCode).toArray(String[]::new);
        String hllShopId = hasBomFoods.get(0).getShopID();
        Map<String, TqlHllShopBillFoodPeriod> map = list1.stream().collect(Collectors.toMap(TqlHllShopBillFoodPeriod::getFoodCode, Function.identity()));
        //补全字段值
        hasBomFoods.forEach(item -> {
            TqlHllShopBillFoodPeriod list1Bom = map.getOrDefault(item.getFoodCode(), new TqlHllShopBillFoodPeriod());
            BigDecimal sumAmount = (null == list1Bom || null == list1Bom.getSumAmount()) ? CommonUtil.zeroBigdecimal : list1Bom.getSumAmount();
            Integer sumcount = (null == list1Bom || null == list1Bom.getCount()) ? 0 : list1Bom.getCount();
            item.setSumAmount(sumAmount);
            item.setSumcount(sumcount);
            BigDecimal bomCost = item.getCost();
            BigDecimal sumAmountBom = CalculatedValueUtil.multiplication(bomCost, sumcount);
            item.setSumAmountBom(sumAmountBom);
        //sumAmount 是售价-出售的金额累加
            //sumAmountBom 是把bom里每道菜品*这段时间卖的份额
            BigDecimal profit = BusinessUtil.getFoodProfit(sumAmount, sumAmountBom);
            BigDecimal profitMargin = BusinessUtil.getFoodProfitMargin(sumAmount, sumAmountBom);
            item.setProfit(profit);
            item.setProfitMargin(profitMargin);
            item.setType(0);
            item.setPandianCode(pandianCode);
            item.setFnumber(fnumber);
            item.setMonth(month+"");
            item.setId(UUID.randomUUID().toString());

        });

        //1.把prolossData拆成 两个集合
        List<TqlStapProloss> periodData1 = new ArrayList<>();
        List<TqlStapProloss> periodData2 = new ArrayList<>();

        for (TqlStapProloss item : prolossData) {
            if (item.getCompareType() == 1) {
                periodData1.add(item);
            } else if (item.getCompareType() == 2) {
                periodData2.add(item);
            }
        }
        //2.查询第一个集合bom物料对应的foodCode
        //arr1里面含有偏大stapCode的集合
        //dishBom里有foodcode
        if(periodData1.size()>0)
        {
            String[] arr1=periodData1.stream().map(TqlStapProloss::getStapCode).toArray(String[]::new);
            //那些菜品含有该物料（成本卡偏大）
            List<String> bomedFoodCodeByBomIsBig=commonService.findfoodCode(hllShopId,arr1);
            if(!CollectionUtils.isEmpty(bomedFoodCodeByBomIsBig))
            for (FoodAndBom item : hasBomFoods) {
                if (bomedFoodCodeByBomIsBig.contains(item.getFoodCode())) {
                    item.setType(item.getType() + 1);
                }
            }
        }
        if(periodData2.size()>0) {
            String[] arr2 = periodData2.stream().map(TqlStapProloss::getStapCode).toArray(String[]::new);
            List<String> bomedFoodCodeByBomIsSmall = commonService.findfoodCode(hllShopId, arr2);
            if(!CollectionUtils.isEmpty(bomedFoodCodeByBomIsSmall))
            for (FoodAndBom item : hasBomFoods) {
                if (bomedFoodCodeByBomIsSmall.contains(item.getFoodCode())) {
                    item.setType(item.getType() + 2);
                }
            }
        }

       // List<FoodAndBom> vos=commonService.findDishBomAndBom(fnumber);

//        @ApiModelProperty("1大 2小")
//        private Integer compareType;
        insertBomcardAnalysAndProfit(pandianCode,hasBomFoods);
        //分析bom偏大还是偏小 //实际成本>理论成本 偏小


    }

    @Transactional
    private int insertBomcardAnalysAndProfit(String pandianCode,List<FoodAndBom> list) {

        commonService.deleteBomcardAnalys(pandianCode);
        return commonService.insertBomcardAnalysAndProfit(list);
    }



//    List<> getStapByDept()
//    {
//
//    }








    public List<TqlStapProloss> insertProloss(String pandianCode, TqlPandianPeriodVO period) throws ParseException {

        //期初
        TqlPandianPeriodVO upperPeriod = commonService.findEnableGenPharseUpper(period.getDeptCode(), period.getPcode());
        String yyyyMMdd = period.getPcode();
        int month = TimeUtil.getMonth(yyyyMMdd, "yyyyMMdd");
        String tqlStapInChange = CommonUtil.TQL_STAP_IN_CHANGE + month;
        String tqlStapOutChange = CommonUtil.TQL_STAP_OUT_CHANGE + month;

        String shopIdStr = commonService.getEnabledHllShopIdByKingdeeFnumber(period.getDeptCode());
        if (StringUtils.isEmpty(shopIdStr)) {
            throw new ServiceException("数据异常，未查到店铺数据！");
        }
        Long shopId = Long.parseLong(shopIdStr);
        //20240223 - 20240229
        Long std = Long.parseLong(TimeUtil.getStringDate(period.getStarttime()));
        Long etd = Long.parseLong(TimeUtil.getStringDate(period.getEndtime()));

        // TODO 所有stapCode集合
        List<TqlStapProlossItem> prolossItemData = new ArrayList<>();
        // TODO 获取期末数据（-）
        List<TqlStapProlossItemVO> periodProloss = commonService.findStapPeriodProloss(pandianCode, std, etd, 5);
        if (periodProloss !=null) {
            for (TqlStapProlossItemVO item : periodProloss) {
                TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 5, -1, item);
                prolossItemData.add(childItem);
            }
        }
        if(null!=upperPeriod) {
            // TODO 获取期初数据（+）
            Long upperStd = Long.parseLong(TimeUtil.getStringDate(upperPeriod.getStarttime()));
            Long upperEtd = Long.parseLong(TimeUtil.getStringDate(upperPeriod.getEndtime()));
            List<TqlStapProlossItemVO> upperPeriodProloss = commonService.findStapPeriodProloss(upperPeriod.getPandianCode(), upperStd, upperEtd, 0);
            if(!CollectionUtils.isEmpty(upperPeriodProloss))
            for (TqlStapProlossItemVO item : upperPeriodProloss) {
                TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 0, 1, item);
                prolossItemData.add(childItem);
            }
        }

        // TODO In_Change 表数据 -----------------------------
        List<TqlStapProlossItemVO> inList = commonService.selectStapInChange(tqlStapInChange, period.getDeptCode(),null, std, etd);
     //   List<TqlStapProlossItemVO> inList = tqlStapProlossMapper.selectStapInChange(tqlStapInChange, period.getDeptCode(),null, std, etd);
        Map<Integer, List<TqlStapProlossItemVO>> groupedMap = inList.stream().collect(Collectors.groupingBy(TqlStapProlossItemVO::getType));
        groupedMap.forEach((mode, deptCodeGroup) -> {
            switch (mode) {
                // TODO 采购（+）
                case 1:
                    for (TqlStapProlossItemVO item : deptCodeGroup) {
                        TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 2, 1, item);
                        prolossItemData.add(childItem);
                    }
                    break;
                case 2:
                    for (TqlStapProlossItemVO item : deptCodeGroup) {
                        TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 2, 1, item);
                        prolossItemData.add(childItem);
                    }
                    break;
                // TODO 调入（+）
                case 3:
                    for (TqlStapProlossItemVO item : deptCodeGroup) {
                        TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 3, 1, item);
                        prolossItemData.add(childItem);
                    }
                    break;
                // TODO 调出（-）
                case 4:
                    for (TqlStapProlossItemVO item : deptCodeGroup) {
                        TqlStapProlossItem childItem = getStapProlossItem(pandianCode, shopId, 4, -1, item);
                        prolossItemData.add(childItem);
                    }
                    break;
                // 可以有更多的 case 语句
                default:
            }
        });
        List<TqlStapProloss> prolossData = new ArrayList<>();
        List<ProlossDetialDto> detialData = new ArrayList<>();

        // TODO 按照 deptCode 和 stapCode 字段进行分组
        Map<String, Map<String, List<TqlStapProlossItem>>> groupedItemMap = prolossItemData.stream()
                .collect(Collectors.groupingBy(TqlStapProlossItem::getDeptCode,
                        Collectors.groupingBy(TqlStapProlossItem::getStapCode)));

        // 打印分组结果
        groupedItemMap.forEach((deptCode, deptCodeGroup) -> {
            System.out.println("deptCode: " + deptCode);
            deptCodeGroup.forEach((stapCode, stapCodeGroup) -> {
                BigDecimal initPrice = BigDecimal.ZERO;
                System.out.println("stapCode: " + stapCode);
                TqlStapProloss vo = new TqlStapProloss();
                vo.setPandianCode(pandianCode);
                vo.setShopCode(shopId+"");
                vo.setDeptCode(deptCode);
                vo.setStapCode(stapCode);
                vo.setPrice(initPrice);
                vo.setInNum(initPrice);
                vo.setInAmout(initPrice);
                vo.setOutNum(initPrice);
                vo.setOutAmout(initPrice);
                vo.setProlossNum(initPrice);
                vo.setProlossAmout(initPrice);
                //实际数量
                BigDecimal inNumAdd = BigDecimal.ZERO;
                //实际金额
                BigDecimal inAmoutAdd = BigDecimal.ZERO;
                //保存到detail
                ProlossDetialDto dto = new ProlossDetialDto();
                dto.setPid(0L);
                dto.setPandianCode(pandianCode);
                dto.setMonth(yyyyMMdd);
                dto.setDeptCode(deptCode);
                dto.setStapCode(stapCode);
                dto.setRemark("无");
                dto.setLastPandianCode(upperPeriod.getPandianCode());
                for (TqlStapProlossItem compute : stapCodeGroup) {
                    compute.setPrice(compute.getPrice());
                    if (compute.getType() == 0) {
                        inNumAdd = inNumAdd.add(compute.getNum());
                        inAmoutAdd = inAmoutAdd.add(compute.getAmout());
                        vo.setPrice(compute.getPrice());
                        //
                        dto.setLastPandianAmount(compute.getAmout());
                        dto.setLastPandianNum(compute.getNum());
                        dto.setLastPandianId(compute.getId());
                        dto.setLastPandianPrice(compute.getPrice());

                    }else if (compute.getType() == 1) {
                        inNumAdd = inNumAdd.add(compute.getNum());
                        inAmoutAdd = inAmoutAdd.add(compute.getAmout());
                        vo.setPrice(compute.getPrice());
                        //
                        dto.setIncaseIds(compute.getIds());
                        dto.setIncaseNum(compute.getNum());
                        dto.setIncaseAmount(compute.getAmout());
                        dto.setIncasePrice(compute.getPrice());
                    }else if (compute.getType() == 2) {
                        inNumAdd = inNumAdd.add(compute.getNum());
                        inAmoutAdd = inAmoutAdd.add(compute.getAmout());
                        vo.setPrice(compute.getPrice());

                        dto.setPurcharseAmount(compute.getAmout());
                        dto.setPurcharseNum(compute.getNum());
                        dto.setPurcharseIds(compute.getIds());
                        dto.setPurcharsePrice(compute.getPrice());
                    } else if (compute.getType() == 3) {
                        inNumAdd = inNumAdd.add(compute.getNum());
                        inAmoutAdd = inAmoutAdd.add(compute.getAmout());
                        vo.setPrice(compute.getPrice());

                        dto.setTransferInNum(compute.getNum());
                        dto.setTransferInAmount(compute.getAmout());
                        dto.setTransferInIds(compute.getIds());
                        dto.setTransferPrice(compute.getPrice());
                    }else if (compute.getType() == 4) {
                        inNumAdd = inNumAdd.subtract(compute.getNum());
                        inAmoutAdd = inAmoutAdd.subtract(compute.getAmout());

                        dto.setTransferOutNum(compute.getNum());
                        dto.setTransferOutAmount(compute.getAmout());
                        dto.setTransferOutIds(compute.getIds());
                        dto.setTransferPrice(compute.getPrice());
                    }else if (compute.getType() == 5) {
                        inNumAdd = inNumAdd.subtract(compute.getNum());
                        inAmoutAdd = inAmoutAdd.subtract(compute.getAmout());

                        dto.setThisPandianNum(compute.getNum());
                        dto.setThisPandianAmount(compute.getAmout());
                        dto.setThisPandianId(compute.getId());
                        dto.setThisPandianPrice(compute.getPrice());
                    }
//                    vo.setPandianCode(compute.getPandianCode());
                    vo.setStapType(compute.getStapType());
                    vo.setStapName(compute.getStapName());
                    vo.setUnitName(compute.getUnitName());
                }
                vo.setInNum(inNumAdd);
                vo.setInAmout(inAmoutAdd);
                vo.setProlossNum(inNumAdd.subtract(vo.getInNum()));
                vo.setProlossAmout(inAmoutAdd.subtract(vo.getInAmout()));
                // 获取标准成本
                TqlStapProlossItemVO standardVo = commonService.findTqlStapOutChange(tqlStapOutChange, deptCode, stapCode, period.getPcode());
                if (standardVo !=null) {
                    vo.setOutNum(standardVo.getStapAmout());
                    vo.setOutAmout(standardVo.getTotalPrice());
                    vo.setProlossNum(standardVo.getStapAmout().subtract(vo.getInNum()));
                    vo.setProlossAmout(standardVo.getTotalPrice().subtract(vo.getInAmout()));

                    //核算数据
                    TqlStapProlossItem item7 = new TqlStapProlossItem();
                    item7.setPandianCode(pandianCode);
                    item7.setShopCode(shopId+"");
                    item7.setDeptCode(deptCode);
                    item7.setStapCode(stapCode);
                    item7.setNum(standardVo.getStapAmout());
                    item7.setAmout(standardVo.getTotalPrice());
                    item7.setPrice(initPrice);
                    item7.setType(7);
                    prolossItemData.add(item7);

                    dto.setOutStapNum(standardVo.getStapAmout());
                    dto.setOutStapAmount(standardVo.getTotalPrice());
                    if (inNumAdd.compareTo(standardVo.getStapAmout())>0){
                        vo.setCompareType(1);
                    }else {
                        vo.setCompareType(2);
                    }
                }
                String uuid=com.ruoyi.common.core.utils.uuid.UUID.randomUUID().toString();
                dto.setUuid(uuid);
                vo.setUuid(uuid);
                detialData.add(dto);
                prolossData.add(vo);
            });
        });
        if (!detialData.isEmpty()) {
            commonService.deleteProlossDetailByPandinacode(pandianCode);
            commonService.insetBatchProlossDetailData(detialData);
        }
        if (!prolossItemData.isEmpty()) {
            commonService.deleteItemByPandinacode(pandianCode);
            commonService.insetBatchProlossItemData(prolossItemData);
        }
        if (!prolossData.isEmpty()) {
            commonService.deleteByPandinacode(pandianCode);
            commonService.insetBatchProlossData(prolossData);
        }
        return prolossData;
    }

    @Override
    public List<TqlHllShopBillFoodPeriod> selectBillFoodPeriod(String pandianCode) {
        return   commonService.selectBillFoodPeriod(pandianCode);
    }

    @Override
    public List<TqlStapProloss> selectProloss(String pandianCode) {
        return   commonService.selectProloss(pandianCode);
    }


    private TqlStapProlossItem getStapProlossItem(String pandianCode, Long shopId, int type, int flag, TqlStapProlossItemVO item) {
        TqlStapProlossItem itemChild = new TqlStapProlossItem();
        itemChild.setPandianCode(pandianCode);
        itemChild.setShopCode(shopId+"");
        itemChild.setType(type);
        itemChild.setIds(item.getIds());
        itemChild.setDeptCode(item.getDeptCode());
        itemChild.setStapType(item.getStapType());
        itemChild.setStapCode(item.getStapCode());
        itemChild.setStapName(item.getStapName());
        itemChild.setUnitName(item.getUnitName());
        itemChild.setNum(item.getStapAmout());
        itemChild.setPrice(item.getStapPrice());
        itemChild.setAmout(item.getTotalPrice());
        itemChild.setFlag(flag);
        return itemChild;
    }

    @Override
    @Slave
    public List<TqlStapProlossItemVO> selectInChange(Integer month, String deptCode, String stapCode, Long std, Long etd) {
        String tqlStapInChange = CommonUtil.TQL_STAP_IN_CHANGE + month;
        return tqlStapProlossMapper.selectStapInChange(tqlStapInChange, deptCode, stapCode, std, etd);
    }

//    @Override
//    public List<TqlStapProlossItemVO> selectInChangeData(Integer month, List<String> deptCodes, List<String> stapCodes, String paramDate) {
//        return null;
//    }
    @Slave
    @Override
    public List<TqlStapProlossItemVO> selectInChangeData(Integer month, List<String> deptCodes, List<String> stapCodes,String paramDate) {
        String tqlStapInChange = CommonUtil.TQL_STAP_IN_CHANGE + month;
        return tqlStapProlossMapper.selectStapInChangeData(tqlStapInChange, deptCodes, stapCodes,paramDate);
    }

    @Override
    public List<Boolean> getGenStatus() {
        return redisService.getCacheList(pandianKey);
    }

    @Override
    public void regen(String pandianCode) throws ParseException {
        TqlPandianPeriodVO period = commonService.findEnableGenPharse(pandianCode);
        List<TqlHllShopBillFoodPeriod> periodData = insertBillFoodPeriodFromBillFoodReport(pandianCode, period);
        //重新计算要把out数据清了，重新弄
        List<TqlStapProloss>   prolossData = insertProloss(pandianCode, period);
        insertBomcardAnalys(pandianCode,periodData,prolossData);
    }

    @Master
    @Transactional
    public void insertFoodPeriodStatAndStapSaleChange(List<FoodDetailReportDayBean> FoodDetailReportDataByStatSum, String fnumber, String month, String pandianCode, Long starttime, Long endtine, List<TqlStapSaleChangeEntity> list1)
    {
        //插入主表tql_food_period_stat
        //插入主表tql_stap_sale_change
        commonService.batchInsertFoodStatByReportDayAndShop(FoodDetailReportDataByStatSum, fnumber, month, pandianCode, starttime, endtine);
        commonService.batchInsertStapSaleChangeByPeriod(list1);
    }



    private List<TqlStapSaleChangeEntity> getStapSaleChange(List<FoodDetailReportDayBean> list,Long sd,Long ed) {
        if(CollectionUtils.isEmpty(list))return null;
        List< TqlStapSaleChangeEntity> allList=new ArrayList<>();
        for (FoodDetailReportDayBean bean:list)
        {
            List<FoodBomEntity> boms=commonService.findFoodBomByFoodCode(bean);
            for(FoodBomEntity bom:boms)
            {

                //tql_stap_sale_change需要
                String stapCode=bom.getStapCode();
                //tql_stap_sale_change需要
                String stapName=bom.getStapName();
                //tql_stap_sale_change需要
                BigDecimal stapQuota=bom.getStapQuota();
                //BOM
                Long bomId=bom.getBomId();
                //物料使用的工作组可以关联物料
                String deptCode=bom.getDeptCode();
                TqlStapSaleChangeEntity entity=new TqlStapSaleChangeEntity();
                entity.setBomId(bomId);
                entity.setStapCode(stapCode);
                entity.setStapName(stapName);
                Integer sumCount=entity.getSumCount();
                BigDecimal bd=CalculatedValueUtil.multiplication(stapQuota,sumCount);
                entity.setSumStapQuota(bd);
                //  CalculatedValueUtil.multiplication(bd,bom.getC)
                entity.setSumStapAmount(bd);
                entity.setSumCount(bean.getFoodCount());
                //工作组
                entity.setKingdeeDeptCode(bom.getDeptCode());
                //店
                entity.setKingdeeShopCode(bean.getFnumber());
                entity.setMonth(bean.getMonth());
                entity.setStartDate(sd);
                entity.setEndDate(sd);
                entity.setPandianCode(bean.getPandianCode());
                allList.add(entity);
            }
            //物料编码，物料名称，部门，dish.fnumber工作组，price物料价格，foodCount,amount物料金额
        }
        return allList;
    }




}
















